有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

向ArrayList中添加元素时引发java异常

我有一个数组列表,我试图向其中添加值,但遇到异常。 我已经多次使用此代码,但仍然无法找出是什么导致了此错误,下面是供您参考的代码

我使用add方法的那一行出现了空指针异常, 以上所有值都将在控制台中打印)

sid = new ArrayList<String>();
Enumeration e = Global.qtutlist.keys();
int qj=0; 
//iterate through Hashtable keys Enumeration
while(e.hasMoreElements())
{
    System.out.println("sid is key and its value id" );
    System.out.println(Integer.parseInt(e.nextElement().toString()));
    try
    {
        sid.add(e.nextElement().toString());
        System.out.println("lenght is "+ sid.size());
    }

    catch(Exception ex)
    {
        System.out.println("caught exception is"+ex.getMessage());

    }
}

共 (6) 个答案

  1. # 1 楼答案

    在循环中调用nextElement()两次,检查一次

    做如下

    while(e.hasMoreElements())
            {   String item = e.nextElement().toString()
                System.out.println("sid is key and its value id" );
                System.out.println(Integer.parseInt(item));
                try{
                sid.add(item);
                System.out.println("lenght is "+ sid.size());
                }catch(Exception ex){
                    System.out.println("caught exception is"+ex.getMessage());
                }
            }
    

    如果显示NumberFormatException,则其中一个字符串不可解析为int

  2. # 2 楼答案

    您正在循环中检查一次e.hasMoreElements(),并调用两次e.nextElement()。每次对nextElement()的调用都会增加内部标记,因此每次枚举中的元素数为奇数,都会得到一个NPE

  3. # 3 楼答案

    您正在使用e.nextElement()两次。这不行。枚举使用迭代器设计模式,这意味着在内部计数器前进到下一个对象之前,只能访问每个元素一次。请注意,hasMoreElements()不推进光标,只有nextElement()推进光标

    将结果存储在局部变量中,并重复使用:

    System.out.println("sid is key and its value id" );
    String str = e.nextElement().toString();
    System.out.println(Integer.parseInt(str));
    try{
        sid.add(str);
        System.out.println("lenght is "+ sid.size());
    }catch(Exception ex){
        System.out.println("caught exception is"+ex.getMessage());
    }
    
  4. # 4 楼答案

    当只检查一次项目存在时,调用nextElement两次

  5. # 5 楼答案

    你在打电话吗

    e.nextElement()
    

    两次。将其存储在变量中,然后对该变量进行操作

    while(e.hasMoreElements()) {
        Object o = e.nextElement();
        // ...
    }
    
  6. # 6 楼答案

    e.nextElement()为null这就是原因,您正在对null执行toString()操作